<!--
 @description 未派发验收任务-开始验收
 @fileName Create.vue
 @author zengqiongying
 @created 2023/06/13 10:28:39
-->
<template>
  <div class="has-foot-pb" style="padding-top: 8px">
    <Card no-mg :round="false" style="margin-top: 0">
      <Cell title="验收门店" :modelValue="formData.sadAddress" custom readonly valueClassName="color-grey-normal" />
      <Cell
        v-if="formData.reportMold === '软装'"
        title="形象督导"
        :modelValue="formData.supervisionImage"
        placeholder="请选择"
        required
        @right="onSearchSupervision"
      />
      <Cell
        v-if="formData.reportMold === '硬装'"
        title="工程监理"
        :modelValue="formData.projectSupervision"
        placeholder="请选择"
        required
        @right="onSearchSupervision"
      />
      <Cell
        title="验收面积(㎡)"
        v-model="formData.acceptArea"
        type="number"
        placeholder="请输入"
        :maxlength="10"
        :right="false"
        is-input
        inputAlign="right"
        required
      />
      <Cell title="门店名称" :modelValue="formData.agentName" valueClassName="color-grey-normal" readonly custom />
      <Cell title="门店编码" :modelValue="formData.storeCode" valueClassName="color-grey-normal" readonly />
      <Cell title="总面积" :modelValue="`${formData.totalArea || ''} ㎡`" valueClassName="color-grey-normal" readonly />

      <Cell
        v-if="pageSource === 'task'"
        title="验收人员"
        :modelValue="formData.ysSpecialist"
        placeholder="请选择"
        @right="onSearchYsUser"
      />
      <Cell v-else title="验收人员" :modelValue="formData.ysSpecialist" readonly />

      <Cell
        title="异常申请数量"
        v-model="formData.abnorNumber"
        type="digit"
        placeholder="请输入"
        :maxlength="4"
        :right="false"
        is-input
        inputAlign="right"
      />
      <Cell
        title="装修项目号"
        v-model="formData.renovationProjectNo"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        inputAlign="right"
        required
      />
      <Cell title="参与人员合照" is-column custom required readonly divider>
        <!-- <AttachmentUpload
          v-if="detail && detail.caid"
          v-model="imagesList"
          viewType="image"
          :imageWidth="56"
          :imageHeight="56"
          :modelId="caid"
        /> -->
        <PartnerPhoto v-if="detail && detail.caid" v-model="imagesList" :modelId="caid" />
      </Cell>
      <Cell title="补充说明" is-column custom readonly>
        <qmp-field v-model="formData.supplementExplain" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>
    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSave">开始验收</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, watch } from 'vue'
  import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import PartnerPhoto from '@/views/components/PartnerPhoto/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import { queryTaskDetail, createSaveTask } from '@/apis/Task'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  import { IAnyKeyObject } from '@/types/common'
  import { initFormData } from '@/utils'

  const none: any[] = [null, undefined, '']
  export default {
    name: 'TaskEdit',
    components: { Card, Cell, PartnerPhoto },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $route = useRoute()
      const $router = useRouter()
      const datas = reactive<IAnyKeyObject>({
        caid: $route.query?.id || '',
        pageSource: $route.query?.source || '',
        detail: {},
        formData: {
          sadAddress: '',
          supervisionImage: '',
          projectSupervision: '',
          acceptArea: '',
          storeCode: '',
          storeAddress: '',
          totalArea: '',
          ysSpecialist: '',
          acceptMold: '',
          reportMold: '',
          abnorNumber: '',
          renovationProjectNo: '',
          agency: '', // 办事处
          agentCode: '', // 经销商编码
          agentName: '', // 经销商名称(经销商编码)
          supplementExplain: ''
        },
        imagesList: [],
        keyboard: {
          show: false
        }
      })
      datas.keyboard = GetKeyboardMixin()

      const getDetailData = () => {
        const caid = datas.caid
        queryTaskDetail(caid).then((res) => {
          const d = res.data || {}
          datas.detail = d
          datas.imagesList = d.files || []
          initFormData(datas.detail, datas.formData)
          if (datas.pageSource !== 'task' && [null, undefined, ''].includes(d.ysSpecialist)) {
            datas.formData.ysSpecialist = $store.getters.userInfo.userName
          }
        })
      }

      // 选择形象督导
      const onSearchSupervision = () => {
        const emitFuncName = 'TaskEditSetSupervision'
        proxy.$SimpleEvents.registerEvent(emitFuncName, (data: any) => {
          onChangeSupervision(data)
        })
        $router.push({
          path: '/search/hrUser',
          query: {
            name: emitFuncName
          }
        })
      }

      const onChangeSupervision = (d: any) => {
        const names = d.map((v: any) => v.staffName)
        if (datas.formData.reportMold === '软装') {
          datas.formData.supervisionImage = names.join(',')
          datas.formData.projectSupervision = ''
        } else {
          datas.formData.projectSupervision = names.join(',')
          datas.formData.supervisionImage = ''
        }
      }

      // 选择验收人员
      const onSearchYsUser = () => {
        const emitFuncName = 'TaskEditSetYsUser'
        proxy.$SimpleEvents.registerEvent(emitFuncName, (data: any) => {
          onChangeYsUser(data)
        })
        $router.push({
          path: '/search/sasUser',
          query: {
            name: emitFuncName
          }
        })
      }

      const onChangeYsUser = (d: any) => {
        const names = d.map((v: any) => v.userName)
        datas.formData.ysSpecialist = names.join(',')
      }

      const onSave = () => {
        const d = { ...datas.formData }
        if (d.reportMold === '硬装') {
          d.supervisionImage = ''
          if (none.includes(d.projectSupervision)) {
            proxy.$toast('请选择工程监理')
            return
          }
        } else {
          d.projectSupervision = ''
          if (none.includes(d.supervisionImage)) {
            proxy.$toast('请选择形象督导')
            return
          }
        }
        if (none.includes(d.acceptArea)) {
          proxy.$toast('请输入验收面积')
          return
        }
        if (none.includes(d.acceptArea)) {
          proxy.$toast('请输入验收面积')
          return
        } else {
          if (isNaN(d.acceptArea)) {
            proxy.$toast('验收面积只能是数字')
            return
          }
          if (Number(d.acceptArea || 0) === 0) {
            proxy.$toast('验收面积必须大于0')
            return
          }
        }

        if (none.includes(d.renovationProjectNo)) {
          proxy.$toast('请输入装修项目号')
          return
        }

        if (datas.imagesList.length === 0) {
          proxy.$toast('请上传参与人员合照')
          return
        }

        if (!none.includes(d.abnorNumber) && isNaN(d.abnorNumber)) {
          proxy.$toast('异常申请数量只能是数字')
          return
        }
        const images = datas.imagesList.map((v: any) => {
          return v
        })
        const data = { ...d, ...{ images, caid: datas.caid } }

        createSaveTask(data).then((res: any) => {
          if (res.success === 1) {
            proxy.$SimpleEvents.emit('refreshTaskItem')
            // 保存进入编辑
            $router.replace({
              path: '/task/detail',
              query: {
                source: $route.query?.source,
                id: datas.caid
              }
            })
          } else {
            proxy.$toast('操作失败')
          }
        })
      }

      onBeforeRouteLeave((to, from, next) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['TaskManagement', 'HardCheckAccept', 'SoftCheckAccept'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
        next()
      })

      getDetailData()

      return {
        ...toRefs(datas),
        onSearchSupervision,
        onSearchYsUser,
        onSave
      }
    }
  }
</script>
<style lang="less" scoped></style>
